#include <stdlib.h>
#include <stdio.h>

void print_binary_table(int n);
void print_binary_table_recursive(int cur_index, int total_bits, char* buffer);

int main(int argc, char** argv){
    int num_bits = 3;
    printf("打印 %d 位二进制数:\n", num_bits);
    print_binary_table(num_bits);

    printf("\n");

    num_bits = 5;
    printf("打印 %d 位二进制数:\n", num_bits);
    print_binary_table(num_bits);
}

void print_binary_table(int n){
    if (n <= 0) {
        if (n == 0) {
            printf(" (empty string)\n");
        }
        return ;
    }
    char* buffer = (char*)malloc(n+1);
    if (buffer == NULL) {
        perror("Failed to allocate buffer");
        exit(EXIT_FAILURE);
    }

    print_binary_table_recursive(0, n, buffer);
    free(buffer);

}

void print_binary_table_recursive(int cur_index, int total_bits, char* buffer){
    if (cur_index == total_bits) {
        buffer[total_bits] = '\0';
        printf("%s\n", buffer);
        return ;
    }

    buffer[cur_index] = '0';
    print_binary_table_recursive(cur_index+1, total_bits, buffer);

    buffer[cur_index] = '1';
    print_binary_table_recursive(cur_index+1, total_bits, buffer);


}



